/* eslint-disable react-refresh/only-export-components */
import type { FC } from 'react'
import { Suspense } from 'react'
import { defer, Await, useLoaderData } from 'react-router-dom'
import { Spin, message } from 'antd'
import type { LoaderFunctionArgs } from 'react-router-dom'
import useArtEditStore, { initArticle, updateCurrent, resetCurrent } from '@/store/art-edit-store'
import { getCateListApi } from '@/api/cate-api.ts'
import ArtEdit from '@/components/article-edit/art-edit'
import { putArticleApi } from '@/api/article-api'
import to from 'await-to-js'

const ArticleEditBox: FC = () => {
  const loaderData = useLoaderData() as { result: [] }
  return (
    <Suspense
      fallback={
        <Spin tip="loading...">
          <div style={{ marginTop: 30 }}></div>
        </Spin>
      }
    >
      <Await resolve={loaderData.result}>
        <ArtEdit />
      </Await>
    </Suspense>
  )
}

export default ArticleEditBox

export const loader = async ({ params }: LoaderFunctionArgs) => {
  resetCurrent()
  return defer({ result: Promise.all([getCateListApi(), initArticle(params.id!)]) })
}

export const action = async () => {
  const article = useArtEditStore.getState().article
  const keys = ['id', 'title', 'cate_id', 'content', 'state', 'cover_img']
  const fd = new FormData()

  keys.forEach((key) => {
    fd.append(key, article[key])
  })

  const [err] = await to(putArticleApi(fd))
  if (err) return null
  message.success('修改成功！')
  updateCurrent()
  return null
}
